/**
 * Copyright (c) 2020 Coder League
 * All rights reserved.
 *
 * File：CybercafeService.java
 * History:
 *         2020年12月30日: Initially created, Chrise.
 */
package club.coderleague.cfss.service.cybercafe;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import club.coderleague.cfss.config.properties.FileUploadSettings;
import club.coderleague.cfss.dao.AreaDao;
import club.coderleague.cfss.dao.CybercafeDao;
import club.coderleague.cfss.dao.CybercafeLogDao;
import club.coderleague.cfss.dao.OrderDao;
import club.coderleague.cfss.dao.UserDao;
import club.coderleague.cfss.domain.beans.CybercafeRegisterRequest;
import club.coderleague.cfss.domain.beans.UserSession;
import club.coderleague.cfss.domain.entities.Cybercafelogs;
import club.coderleague.cfss.domain.entities.Cybercafes;
import club.coderleague.cfss.domain.entities.Users;
import club.coderleague.cfss.domain.enums.EntHandleType;
import club.coderleague.cfss.domain.enums.EntityState;
import club.coderleague.cfss.domain.enums.UserType;
import club.coderleague.cfss.exceptions.FileUploadException;
import club.coderleague.cfss.util.CommonUtil;
import club.coderleague.cfss.util.FileUtil;
import club.coderleague.data.jpa.domain.Page;

/**
 * 网吧服务。
 * @author Chrise
 */
@Service
public class CybercafeService {
	private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3456789]\\d{9}$");
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private CybercafeDao cybercafeDao;
	@Autowired
	private CybercafeLogDao clDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private AreaDao areaDao;
	@Autowired
	private FileUploadSettings fuSettings;
	
	/**
	 * 注册网吧。
	 * @author Chrise 2020年12月30日
	 * @param request 注册请求。
	 * @param buslicense 营业执照。
	 * @return 注册结果。
	 */
	public String execRegisterCybercafe(CybercafeRegisterRequest request, MultipartFile buslicense) {
		if (!PHONE_PATTERN.matcher(request.getContactnumber()).matches()) return "无效的联系电话！";
		if (this.cybercafeDao.existsCybercafe(request.getEntname(), request.getBuslicenseno(), null)) return "网吧信息已存在！";
		if (this.userDao.existsByLoginnameOrUserphoneNotEntityid(null, request.getContactnumber(), null)) return "无法用联系电话创建账户！";
		
		String buslicensePath = null;
		try {
			buslicensePath = FileUtil.saveFile(buslicense, this.fuSettings.getRootReal() + this.fuSettings.getBuslicensePath(), 
				this.fuSettings.getBuslicenseType(), this.fuSettings.getCommonAttachSize());
		} catch (FileUploadException e) {
			switch (e.getFueCode()) {
				case FILE_INVALID:
					return "营业执照文件无效！";
				case ILLEGAL_TYPE:
					return "营业执照文件类型错误！";
				case TOO_BIG:
					return "营业执照文件太大！";
			}
		} catch (Exception e) {
			return "保存营业执照文件错误！";
		}
		
		Date date = new Date();
		
		Cybercafes cybercafe = new Cybercafes(EntityState.AUDITING.getValue(), request.getEntname(), request.getBuslicenseno(), buslicensePath, 
			request.getLeader(), request.getContactnumber(), request.getProvinceid(), request.getCityid(), request.getDistrictid(), request.getStreetid(), 
			request.getDetailaddr(), date, null, null);
		this.cybercafeDao.save(cybercafe);
		
		Cybercafelogs log = new Cybercafelogs(EntityState.VALID.getValue(), cybercafe.getEntityid(), null, EntHandleType.SUBMIT_DATA.getValue(), date);
		this.clDao.save(log);
		
		Users user = new Users();
		user.setEntitystate(EntityState.VALID.getValue());
		user.setCybercafeid(cybercafe.getEntityid());
		user.setUsertype(UserType.NORMAL.getValue());
		user.setUserphone(cybercafe.getContactnumber());
		this.userDao.save(user);
		
		return null;
	}
	
	/**
	 * 查询网吧分页数据。
	 * @author Chrise 2020年12月30日
	 * @param states 状态。
	 * @param keyword 关键字。
	 * @param pageIndex 分页索引。
	 * @param pageSize 分页大小。
	 * @return 网吧分页数据。
	 */
	public Page<Map<String, Object>> queryCybercafePageData(String states, String keyword, Integer pageIndex, Integer pageSize) {
		List<Integer> list = new ArrayList<Integer>();
		if (CommonUtil.isEmpty(states)) {
			list.add(EntityState.AUDITING.getValue());
			list.add(EntityState.OPENING.getValue());
		} else {
			String[] array = states.split(",");
			for (String s : array) {
				list.add(Integer.valueOf(s));
			}
		}
		
		String buslicensePath = this.fuSettings.getRootVirtual() + this.fuSettings.getBuslicensePath();
		
		return this.cybercafeDao.queryCybercafePageData(list, keyword, buslicensePath, pageIndex, pageSize);
	}
	
	/**
	 * 修改网吧状态。
	 * @author Chrise 2020年12月30日
	 * @param entityids 实体标识。
	 * @param state 实体状态。
	 * @param us 用户会话。
	 */
	public void updateState(String entityids, int state, UserSession us) {
		Date date = new Date();
		String[] array = entityids.split(",");
		for (String entityid : array) {
			Cybercafes cybercafe = this.cybercafeDao.getOne(Long.valueOf(entityid));
			cybercafe.setEntitystate(state);
			cybercafe.setAuditor(us.getId());
			cybercafe.setAudittime(date);
			
			Cybercafelogs log = new Cybercafelogs(EntityState.VALID.getValue(), cybercafe.getEntityid(), us.getId(), EntHandleType.AUDIT_DATA.getValue(), date);
			this.clDao.save(log);
		}
	}
	
	/**
	 * 查询网吧详情数据。
	 * @author Chrise 2020年12月30日
	 * @param entityid 实体标识。
	 * @return 网吧详情数据。
	 */
	public Map<String, Object> queryCybercafeDetail(long entityid) {
		String buslicensePath = this.fuSettings.getRootVirtual() + this.fuSettings.getBuslicensePath();
		
		Map<String, Object> cybercafe = this.cybercafeDao.queryCybercafeDetail(entityid, buslicensePath);
		return cybercafe;
	}
	
	/**
	 * 检查网吧状态。
	 * @author Chrise 2021年1月12日
	 * @param session 用户会话。
	 * @return 检查结果。
	 */
	public Map<String, Object> checkCybercafeState(UserSession session) {
		Integer state = this.cybercafeDao.queryCybercafeState(session.getOrgid());
		if (state == null || EntityState.DELETED.equalsValue(state)) return null;
		
		int orderNumber = this.orderDao.queryHandlingNumber(session.getOrgid(), false);
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("cybercafeState", EntityState.OPENING.equalsValue(state));
		result.put("orderNumber", orderNumber);
		return result;
	}
	
	/**
	 * 加载个人信息。
	 * @author Chrise 2021年2月10日
	 * @param session 用户会话。
	 * @return 个人信息。
	 */
	public Map<String, Object> loadPersonalInfo(UserSession session) {
		Map<String, Object> cybercafe = this.cybercafeDao.queryPersonalInfo(session.getOrgid());
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("cybercafe", cybercafe);
		return result;
	}
	
	/**
	 * 加载网吧数据。
	 * @author Chrise 2021年2月10日
	 * @param session 用户会话。
	 * @return 网吧数据。
	 */
	public Map<String, Object> loadCybercafeData(UserSession session) {
		String buslicensePath = this.fuSettings.getRootVirtual() + this.fuSettings.getBuslicensePath();
		
		Map<String, Object> cybercafe = this.cybercafeDao.queryCybercafeData(session.getOrgid(), buslicensePath);
		
		Map<String, List<Map<String, Object>>> areas = new HashMap<String, List<Map<String,Object>>>();
		areas.put("0", this.areaDao.getAreasForMobileSelect(null));
		
		Long provinceid = (Long)cybercafe.get("provinceid");
		areas.put(provinceid.toString(), this.areaDao.getAreasForMobileSelect(provinceid));
		Long cityid = (Long)cybercafe.get("cityid");
		areas.put(cityid.toString(), this.areaDao.getAreasForMobileSelect(cityid));
		Long districtid = (Long)cybercafe.get("districtid");
		areas.put(districtid.toString(), this.areaDao.getAreasForMobileSelect(districtid));
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("cybercafe", cybercafe);
		result.put("areas", areas);
		return result;
	}
	
	/**
	 * 重新提交网吧。
	 * @author Chrise 2021年2月10日
	 * @param request 注册请求。
	 * @param buslicense 营业执照。
	 * @param session 用户会话。
	 * @return 提交结果。
	 */
	public String execResubmitCybercafe(CybercafeRegisterRequest request, MultipartFile buslicense, UserSession session) {
		if (!PHONE_PATTERN.matcher(request.getContactnumber()).matches()) return "无效的联系电话！";
		if (this.cybercafeDao.existsCybercafe(request.getEntname(), request.getBuslicenseno(), session.getOrgid())) return "网吧信息已存在！";
		
		String buslicensePath = null;
		if (buslicense != null) {
			try {
				buslicensePath = FileUtil.saveFile(buslicense, this.fuSettings.getRootReal() + this.fuSettings.getBuslicensePath(), 
					this.fuSettings.getBuslicenseType(), this.fuSettings.getCommonAttachSize());
			} catch (FileUploadException e) {
				switch (e.getFueCode()) {
					case FILE_INVALID:
						return "营业执照文件无效！";
					case ILLEGAL_TYPE:
						return "营业执照文件类型错误！";
					case TOO_BIG:
						return "营业执照文件太大！";
				}
			} catch (Exception e) {
				return "保存营业执照文件错误！";
			}
		}
		
		Date date = new Date();
		
		Cybercafes cybercafe = this.cybercafeDao.getOne(session.getOrgid());
		cybercafe.setEntname(request.getEntname());
		cybercafe.setBuslicenseno(request.getBuslicenseno());
		cybercafe.setLeader(request.getLeader());
		cybercafe.setContactnumber(request.getContactnumber());
		cybercafe.setProvinceid(request.getProvinceid());
		cybercafe.setCityid(request.getCityid());
		cybercafe.setDistrictid(request.getDistrictid());
		cybercafe.setStreetid(request.getStreetid());
		cybercafe.setDetailaddr(request.getDetailaddr());
		cybercafe.setEntitystate(EntityState.AUDITING.getValue());
		cybercafe.setApplytime(date);
		if (buslicensePath != null) cybercafe.setBuslicense(buslicensePath);
		
		Cybercafelogs log = new Cybercafelogs(EntityState.VALID.getValue(), cybercafe.getEntityid(), session.getId(), EntHandleType.SUBMIT_DATA.getValue(), date);
		this.clDao.save(log);
		
		return null;
	}
}
